//
//  MYPublishAliVideoViewController.m
//  MiaoYin
//
//  Created by DarkWorld on 2021/11/22.
//  Copyright © 2021 thy. All rights reserved.
//

#import "MYPublishAliVideoViewController.h"
#import "MYSelectCoverView.h"
#import "MYSelectChannelView.h"
#import "MYChannelModel.h"
#import "MYSystemAlertView.h"
#import "BaseUINavigationButton.h"

#import "MYPublishVideo_Cell.h"

#import "AlivcShortVideoUploadManager.h"
#import <AFNetworking/AFNetworking.h>


@interface MYPublishAliVideoViewController ()<QMUITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,AlivcShortVideoUploadManagerDelegate>
{
    MYChannelModel *my_model;
    NSURL *my_videoUrl;
}
@property (nonatomic,strong) QMUITextView *textView;
@property (nonatomic,strong) UIImageView *coverImgView;
@property (nonatomic,strong) UILabel *addresslabel;
@property (nonatomic,strong) NSArray *itemArray;
@property (nonatomic,copy) NSString *coverUrlStr;
@property (nonatomic,copy) NSString *vidioUrlStr;
@property(nonatomic, strong) NSString *titleS;


/// 选择频道
@property(nonatomic, strong) MYPublishVideo_Cell *selectChannelCell;

@property(nonatomic, strong) AlivcShortVideoUploadManager *uploadManager;



@end

@implementation MYPublishAliVideoViewController
- (UITextView *)textView
{
    if(!_textView)
    {
        _textView = [[QMUITextView alloc] init];
        _textView.font = [UIFont systemFontOfSize:14];
        _textView.backgroundColor = [UIColor whiteColor];
        _textView.returnKeyType = UIReturnKeyDone;
        _textView.layoutManager.allowsNonContiguousLayout = NO;
        _textView.delegate = self;
        _textView.enablesReturnKeyAutomatically = YES;
        _textView.textColor = MY_Text_Color_Theme1;
        _textView.placeholder = @"分享我的心情";
        _textView.maximumTextLength = 50;
    }
    return _textView;
}

- (UIImageView *)coverImgView
{
    if (!_coverImgView)
    {
        _coverImgView = [[UIImageView alloc] init];
        _coverImgView.contentMode = UIViewContentModeScaleAspectFill;
        _coverImgView.clipsToBounds = YES;
        _coverImgView.userInteractionEnabled = YES;
        _coverImgView.layer.cornerRadius = 6;
        _coverImgView.image = self.coverImage;
        
//        UILabel *hintLabel = [[UILabel alloc] init];
//        hintLabel.textColor = [UIColor whiteColor];
//        hintLabel.font = [UIFont systemFontOfSize:12];
//        hintLabel.text = @"更改封面";
//        hintLabel.textAlignment = NSTextAlignmentCenter;
//        hintLabel.backgroundColor = [UIColor colorWithUInt:0x000000 alpha:0.5];
//        [_coverImgView addSubview:hintLabel];
//
//        [hintLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.right.bottom.equalTo(_coverImgView);
//            make.height.equalTo(@36);
//        }];
    }
    return _coverImgView;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self layout];
    [self loadDataWithShow:NO];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)setupNavigationItems
{
    [super setupNavigationItems];
    
    BaseUINavigationButton *leftButton = [[BaseUINavigationButton alloc] initWithType:QMUINavigationButtonTypeImage];
    leftButton.frame = CGRectMake(0, 0, (44), (44));
    [leftButton setImage:UIImageMake(@"appNav_back") forState:UIControlStateNormal];
    UIBarButtonItem *leftItem = [UIBarButtonItem qmui_itemWithButton:leftButton target:self action:@selector(goBackAction)];
    self.navigationItem.leftBarButtonItems = @[leftItem];
    
    UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    submitButton.frame = CGRectMake(0, 0, 67, (30));
    submitButton.backgroundColor = MY_ColourMatchingSpecifications_Theme1;
    submitButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [submitButton setTitle:@"发布" forState:UIControlStateNormal];
    [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    submitButton.layer.masksToBounds = YES;
    submitButton.layer.cornerRadius = 4;
    UIBarButtonItem * Item = [UIBarButtonItem qmui_itemWithButton:(QMUINavigationButton *)submitButton target:self action:@selector(didSelectSubmitAction)];

    self.navigationItem.rightBarButtonItems = @[Item];
}

- (void)layout
{
    [self.view addSubview:self.textView];
    [self.view addSubview:self.coverImgView];
    
    UIView *addressView = [[UIView alloc] init];
    addressView.backgroundColor = [UIColor whiteColor];
    addressView.clipsToBounds = YES;
    addressView.hidden = YES;
    [self.view addSubview:addressView];
    
    UIImageView *img = [[UIImageView alloc] init];
    img.image = [UIImage imageNamed:@"ic_address_small_gray"];
    [addressView addSubview:img];
    
//    self.addresslabel = [[UILabel alloc] init];
//    self.addresslabel.textColor = MY_Text_Color_Theme1;
//    self.addresslabel.font = [UIFont systemFontOfSize:14];
//    self.addresslabel.text = @"选择地址";
//    self.addresslabel.textAlignment = NSTextAlignmentLeft;
//    [addressView addSubview:self.addresslabel];
//    
//    UIImageView *arrowImg = [[UIImageView alloc] init];
//    arrowImg.image = [UIImage imageNamed:@"ic_arrow_right"];
//    [addressView addSubview:arrowImg];
//    
//    UIView *lineView = [[UIView alloc] init];
//    lineView.backgroundColor = MY_ColourMatchingSpecifications_Line;
//    [addressView addSubview:lineView];
    
    {
        NSInteger width = (SCREEN_WIDTH - 60) / 2;
        
        [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(MY_Padding));
            make.right.equalTo(@(-MY_Padding));
            make.top.equalTo(@(self.topControlHeight+20));
            make.height.equalTo(@110);
        }];
        
        [self.coverImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.textView);
            make.width.equalTo(@(width));
            make.height.equalTo(@(width/150*200));
            make.top.equalTo(self.textView.mas_bottom).offset(10);
        }];
        
        
        [addressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.height.equalTo(@40);
            make.top.equalTo(self.coverImgView.mas_bottom).offset(20);
        }];
        
        [img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(MY_Padding));
            make.centerY.equalTo(addressView);
            make.width.height.equalTo(@18);
        }];
        
//        [self.addresslabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerY.height.equalTo(addressView);
//            make.left.equalTo(img.mas_right).offset(10);
//            make.right.equalTo(@(-46));
//        }];
//
//        [arrowImg mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerY.equalTo(addressView);
//            make.right.equalTo(@(-MY_Padding));
//        }];
//
//        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.equalTo(self.addresslabel);
//            make.right.equalTo(@(-MY_Padding));
//            make.height.equalTo(@(0.5));
//            make.bottom.equalTo(addressView);
//        }];
    }
    
    [self.coverImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didSelectCoverAction)]];
    [addressView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didSelectAddressAction)]];
    

//        MYPublishVideo_Cell *cell1 = [[MYPublishVideo_Cell alloc] init];
//        cell1.leftImageView.image = UIImageMake(@"Video_Record_PinDao");
//        cell1.titleLabel.text = @"选择频道";
//        [self.view  addSubview:cell1];
//        [cell1 mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.right.equalTo(self.view);
//            make.height.equalTo(@63);
//            make.top.equalTo(self.coverImgView.mas_bottom).offset(20);
//        }];
//        [cell1 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(channelButtonTouchUpInside)]];
//
//        self.selectChannelCell = cell1;
    
    
    
    

}

- (void)loadDataWithShow:(BOOL)isShow
{
//    MY_WEAK;
//    [MYRequesTool MY_live_Vod_getVodType_RequestWithParams:@{} successHandle:^(id  _Nonnull response) {
//
//        weakSelf.itemArray = [NSArray yy_modelArrayWithClass:[MYChannelModel class] json:response[@"data"]];
//        [MYTipUtils hideAllTipsInView:weakSelf.view];
//
//        if (isShow)
//        {
//            [weakSelf channelButtonTouchUpInside];
//        }
//
//    } failureHandle:^(NSError * _Nonnull error) {
//        [MYTipUtils hideAllTipsInView:weakSelf.view];
//    }];
}

//选择封面
- (void)didSelectCoverAction
{
    [self.view endEditing:YES];
    
    
}

//选择地址
- (void)didSelectAddressAction
{
    
}

/// 选择电商
- (void)selectStore
{
    
}

//选择频道
- (void)channelButtonTouchUpInside
{
    [self.view endEditing:YES];
    
    if (self.itemArray.count > 0)
    {
        MY_WEAK;
        MYSelectChannelView *v = [[MYSelectChannelView alloc] init];
        [v showWithArray:self.itemArray completion:^(MYChannelModel *model) {
            
            self->my_model = model;
            self.selectChannelCell.titleLabel.text = [NSString stringWithFormat:@"%@",model.typeName];
        }];
    }
    else
    {
        [MYTipUtils showLoadingAlertString:@"" inView:self.view];
        [self loadDataWithShow:YES];
    }
}

//发布
- (void)didSelectSubmitAction
{
    [self.view endEditing:YES];
    
    if (self.textView.text.length == 0)
    {
        [MYTipUtils showAlertString:@"请填写发布内容"];
        return;
    }
 
    [self uploadVidio];

}

- (void)uploadVidio
{
    [MYTipUtils showLoadingAlertString:@"视频发布中..." inView:self.view];
    NSString *coverPath = [_taskPath stringByAppendingPathComponent:@"cover.png"];
    NSData *data = UIImagePNGRepresentation(_coverImage);
    [data writeToFile:coverPath atomically:YES];
    AliyunUploadSVideoInfo *info = [AliyunUploadSVideoInfo new];
    info.title = self.textView.text;
    info.desc = self.textView.text;
    self.titleS = self.textView.text;
    _uploadManager = [AlivcShortVideoUploadManager shared];
    [_uploadManager setCoverImagePath:coverPath videoInfo:info videoPath:_config.outputPath];
    _uploadManager.managerDelegate = self;
    [_uploadManager startUpload];
    [self startNetworketingMonitoring];
}

- (void)submitNimData:(NSString *)vid
{
    
//    NSDictionary *dict = @{
//           @"title":self.textView.text,
//           @"typeId":[NSString stringWithFormat:@"%ld",my_model.typeId],
//           @"vodImg":self.coverUrlStr,
//           @"vid":[NSString stringWithFormat:@"%@",vid],
//           @"vodMusicId":self.crrentAudioModel?[NSString stringWithFormat:@"%@",self.crrentAudioModel.vodMusicId]:@"",
//           @"extensionGoods":self.storeModel?@(self.storeModel.goodsId):@"",
//
//       };
//
//       MY_WEAK;
//       [MYRequesTool MY_live_Vod_uploadVodByVid_RequestWithParams:dict successHandle:^(id  _Nonnull response) {
//
//           MYSystemAlertView *v = [[MYSystemAlertView alloc] init];
//           v.my_title = @"作品已发布，等待审核中";
//           v.my_content = @"等待人工审核通过后即可发布成功";
//           v.my_rightButtonTitle = @"知道了";
//           v.my_rightButtonTextColor = MY_ColourMatchingSpecifications_Theme1;
//           [v showOnlyOneButtonWithCompletion:^(MYSystemAlertView * _Nonnull vc) {
//
//               [weakSelf.navigationController popToRootViewControllerAnimated:YES];
//           }];
//
//           [MYTipUtils hideAllTipsInView:weakSelf.view];
//       } failureHandle:^(NSError * _Nonnull error) {
//           [MYTipUtils hideAllTipsInView:weakSelf.view];
//       }];
}


//根据本地路径获取视频的第一帧
- (UIImage*)getVideoPreViewImage:(NSURL *)url
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *img = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return img;
}

#pragma mark - Priva Action
- (void)updateUploadLabelWithProgress:(CGFloat)progress {
    if (progress < 0) {
        return;
    }
    if (progress < 1) {
        //正在上传
    } else {
        //视频上传成功
    }

}
- (void)startNetworketingMonitoring{
    __weak typeof(self)weakSelf = self;
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if ((status != AFNetworkReachabilityStatusNotReachable) && (weakSelf.uploadManager.currentStatus>1)) {
            [weakSelf.uploadManager startUpload];
        }
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
- (UIView *)addCell:(NSString *)leftIcon  title:(NSString *)title  action:(SEL)action
{
    UIView *view = [[UIView alloc] init];
    [self.view addSubview:view];
    //icon
    UIImageView *leftImage = [[UIImageView alloc] init];
    leftImage.image = UIImageMake(leftIcon);
    [view addSubview:leftImage];
    [leftImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(MY_Padding);
        make.centerY.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(18, 18));
    }];
    
    //文字
    UILabel *label = [[UILabel alloc] init];
    label.numberOfLines = 1;
    label.text = title;
    label.font = [UIFont systemFontOfSize:16];
    label.textColor = MY_Text_Color_Theme1;
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftImage.mas_right).offset(10);
        make.centerY.mas_equalTo(0);
    }];
    
    //右箭头
    UIImage *image = UIImageMake(MYCell_rightArrow_ImageName);
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = image;
    [view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(image.size);
        make.right.mas_equalTo(-MY_Padding);
        make.centerY.equalTo(view);
        
    }];
    
    //横线
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = MYCell_Line_Color;
    [view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(MY_Padding);
        make.right.mas_equalTo(-MY_Padding);
        make.bottom.equalTo(view);
        make.height.mas_equalTo(1);
    }];
    
    
    
    return view;
}

#pragma mark - AlivcShortVideoUploadManagerDelegate
- (void)uploadManager:(AlivcShortVideoUploadManager *)manager updateProgress:(CGFloat)progress {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updateUploadLabelWithProgress:progress];

    });
}

- (void)uploadManager:(AlivcShortVideoUploadManager *)manager uploadStatusChangedTo:(AlivcUploadStatus)newStatus {
    switch (newStatus) {
        case AlivcUploadStatusFailure: {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MYTipUtils hideAllTipsInView:self.view];

                
                     UIAlertController *alertController =[UIAlertController alertControllerWithTitle:NSLocalizedString(@"上传失败" , nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
                        
                UIAlertAction *action =[UIAlertAction actionWithTitle:NSLocalizedString(@"确定" , nil) style:UIAlertActionStyleDefault handler:nil];
                        [alertController addAction:action];
                
                        [self presentViewController:alertController animated:YES completion:nil];
                
                
            });
        } break;
        case AlivcUploadStatusSuccess: {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
                
                           });
        } break;
        default:
            break;
    }
}
     
/**
上传完成回调

@param manager manager
@param vid 视频id
@param imageUrl 封面url
*/
- (void)uploadManager:(AlivcShortVideoUploadManager *)manager
                          succesWithVid:(NSString *)vid
                          coverImageUrl:(NSString *)imageUrl
{
   

    
//        阿里上传成功 现在变成关联自己服务器
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
        [MYTipUtils hideAllTipsInView:self.view];

        MYSystemAlertView *v = [[MYSystemAlertView alloc] init];
        v.my_title = @"作品已发布，等待审核中";
        v.my_content = @"等待人工审核通过后即可发布成功";
        v.my_rightButtonTitle = @"知道了";
        v.my_rightButtonTextColor = MY_ColourMatchingSpecifications_Theme1;
        [v showOnlyOneButtonWithCompletion:^(MYSystemAlertView * _Nonnull vc) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{

                [self.navigationController popToRootViewControllerAnimated:YES];

            });
        }];

    });
        DLog(@"阿里的数据上传成功，vodid:%@",vid);
}
     
#pragma mark - QMUITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        return NO;
    }
    return YES;
}

#pragma mark -- UIImagePickerControllerDelegate
/// 用户选择相片(选取编辑过的图片)
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = nil;
    if ([info objectForKey:UIImagePickerControllerEditedImage])
    {
        image = [info objectForKey:UIImagePickerControllerEditedImage];
    }
    else
    {
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    self.coverImgView.image = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

/// 用户选择取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)goBackAction
{
    [self.navigationController popViewControllerAnimated:YES];
}




@end
